package org.gd.spring.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static volatile HibernateUtil INSTANCE = null;
    private SessionFactory sessionFactory;

    public static HibernateUtil getInstance() {
        if(INSTANCE == null) {
            synchronized (HibernateUtil.class) {
                if (INSTANCE == null) {
                    INSTANCE = new HibernateUtil();
                }
            }
        }
        return INSTANCE;
    }

    public HibernateUtil() {
        sessionFactory = buildSessionFactory();
    }

    /**
     * Create the SessionFactory from hibernate.cfg.xml
     *
     * @return SessionFactory
     */
    @SuppressWarnings("deprecation")
    private SessionFactory buildSessionFactory() {
        try {
            return new Configuration()
                    .configure("/hibernate/hibernate.cfg.xml")
                    .buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void shutdown() {
        getSessionFactory().close();
    }

    public Session openSession() {
        return getSessionFactory().openSession();
    }

}